package com.raymond.utils;

import com.raymond.httpclient.annotation.ServerScan;
import com.raymond.httpclient.cache.ServerCaches;
import com.raymond.httpclient.proxy.HttpServerProxy;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 服务加载类
 *
 * @author :  raymond
 * @version :  V1.0
 * @date :  2021-04-01 10:47
 */
public class ServerLoadUtil {
    private static final Map<Class<?>, HttpServerProxy> SERVER_CACHES_MAP = new HashMap<Class<?>, HttpServerProxy>();

    @SuppressWarnings("unchecked")
    public static <T> T getHttpServerProxy(Class<?> aClass) {
        return (T) SERVER_CACHES_MAP.get(aClass).getObj();
    }

    static {
        Class<?> aClass = ClassUtils.deduceMainApplicationClass();
        if (aClass != null) {
            ServerScan annotation = aClass.getAnnotation(ServerScan.class);
            if (annotation != null) {
                setPackageNameList(annotation.basePackages());
            }
        }
    }

    private static void setPackageNameList(String[] basePackages) {
        try {
            Set<Class<?>> classes = ClassUtils.getClasses(basePackages);
            loadClass(classes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void loadClass(Set<Class<?>> classes) {
        for (Class<?> aClass : classes) {
            ServerCaches serverCaches = new ServerCaches(aClass);
            if (!serverCaches.init()) {
                continue;
            }
            HttpServerProxy httpServerProxy = new HttpServerProxy(serverCaches);
            SERVER_CACHES_MAP.put(aClass, httpServerProxy);
        }
    }

}
